import {
  indexApi
} from '../../api/index';
import {
  request
} from '../../utils/request';

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    addressList: {
      type: Array,
      value: []
    },
    selectedAddressId: {
      type: String,
      value: ''
    },
    addressPop: {
      type: Boolean,
      value: false,
      observer(newVal) {
        console.log("刷新==========");
        if (newVal) {
          this.getAddress();
        }
      }
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    addressList: [],
    pageNum: 0,
    pageSize: 10,
    firstname: "",
    selectedAddressId: '1',
    selectedAddress: "",
    isEmpty: false
  },

  /**
   * 组件的生命周期函数列表
   */
  lifetimes: {
    attached() {
      this.getAddress();
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onEnter() {
      console.log("刷新");
      this.getAddress();
    },
    // 收货地址列表
    async getAddress() {
      try {
        const res = await request({
          url: indexApi.addressApi(),
          data: {
            pageNum: this.data.pageNum,
            pageSize: this.data.pageSize
          }
        });

        console.log("res.data====", res.data);
        // 检查数组是否为空并设置isEmpty
        if (res.data.length == 0) {
          console.log("为空");
          this.setData({
            isEmpty: false
          });
        } else {
          this.setData({
            isEmpty: true
          });
        }

        const addressList = res.data.map(item => ({
          ...item,
          firstname: item.nickName.charAt(0)
        }));

        // 找到最后一个 is_default: 0 的地址
        const lastDefaultIndex = addressList.map(item => item.is_default).lastIndexOf(0);
        if (lastDefaultIndex !== -1) {
          // 标记最后一个 is_default: 0 的地址
          addressList[lastDefaultIndex].isLastDefault = true;

          // 将最后一个 is_default: 0 的地址移动到列表顶部
          const lastDefaultItem = addressList.splice(lastDefaultIndex, 1)[0];
          addressList.unshift(lastDefaultItem);
        }

        this.setData({
          addressList: addressList
        });

        console.log("res", res);
        console.log("addressList", this.data.addressList);
      } catch (error) {
        console.error("Error:", error);
      }
    },

    onChange(event) {
      //拼接地址
      console.log("Radio value changed: ", event);
      const selectedAddressId = event.detail;
      const selectedAddressObj = this.data.addressList.find(item => item.addressId == selectedAddressId);
      const selectedAddress = `${selectedAddressObj.province} ${selectedAddressObj.city} ${selectedAddressObj.area} ${selectedAddressObj.detail}`;
      console.log("selectedAddress", selectedAddress);

      this.setData({
        selectedAddressId: selectedAddressId,
        selectedAddress: selectedAddress
      });
      this.triggerEvent('selectedAddressId', {
        selectedAddressId,
        selectedAddress
      });
    },

    besure() {
      this.triggerEvent('besure', {
        selectedAddressId: this.data.selectedAddressId,
        selectedAddress: this.data.selectedAddress
      });
    },


    //添加收货地址
    addAddress(){
      wx.navigateTo({
        url: '/packageUserCenter/pages/addAddress/index?fromPage=1',
      })
      this.triggerEvent('closeAddress');
    }
  }
});